<?php
declare(strict_types=1);

namespace app\common\business;

use app\common\model\mysql\Address as AddressModel;
use think\Exception;

class Address extends BusiBase
{
    public function __construct()
    {
        $this->model = new AddressModel();
    }

    /**
     * 获取指定条件地址数据
     *
     * @param array $condition
     * @return array
     */
    public function getLists(array $condition = [])
    {
        try {
            $result = $this->model->getNormalAllDataByCondition($condition);
        } catch (\Exception $e) {
            $this->errorLog('find data by '.json_encode($condition)." error: ".$e->getMessage());
            return [];
        }
        if (!$result) return [];
        $data = $result->toArray();
        return $data;
    }

    /**
     * 获取单条地址原始数据
     *
     * @param int $id
     * @return array
     */
    public function getNormalById(int $id)
    {
        try {
            $data = AddressModel::find($id);
            $result = $data->getData();
        } catch (\Exception $e) {
            $this->errorLog("get yuanshu data By $id error: ".$e->getMessage());
            return [];
        }
        if (!$result) return [];
        return $result;
    }

    /**
     * 用户地址添加
     *
     * @param array $data
     * @return false|mixed
     * @throws Exception
     */
    public function add(array $data)
    {
        $check = $data;
        unset($check['is_default']);
        try {
            $find = $this->model->getNormalDataByCondition($check);
        } catch (\Exception $e) {
            $this->errorLog('find data by '.json_encode($check)." error: ".$e->getMessage());
            throw new Exception('服务器内部错误');
        }
        if ($find) throw new Exception('当前数据已存在');

        $this->model->startTrans();
        try {
            if ($data['is_default']) {
                $res = $this->editAll(['uid' => $data['uid']], ['is_default' => 0]);
                if (!$res) return false;
            }
            $insertId = $this->insert($data);
            $this->model->commit();
        } catch (\Exception $e) {
            $this->model->rollback();
            $this->errorLog('add address '.json_encode($data)." error: ".$e->getMessage());
            throw new Exception('服务器内部错误');
        }

        return $insertId;
    }

    /**
     * 根据数据 ID 修改地址信息
     *
     * @param int $id
     * @param array $data
     * @return false|mixed
     * @throws Exception
     */
    public function updateAddressById(int $id, array $data)
    {
        $check = $data;
        try {
            $find = $this->model->getNormalDataByCondition($check);
        } catch (\Exception $e) {
            $this->errorLog('find data by '.json_encode($check)." error: ".$e->getMessage());
            throw new Exception('服务器内部错误');
        }
        if ($find && $find['id'] == $id) throw new Exception('该数据无需修改');

        $this->model->startTrans();
        try {
            if ($data['is_default']) {
                $res = $this->editAll(['uid' => $data['uid']], ['is_default' => 0]);
                if (!$res) return false;
            }
            $update = $this->edit($id, $data);
            $this->model->commit();
        } catch (\Exception $e) {
            $this->model->rollback();
            $this->errorLog('update address id:'.$id." to ".json_encode($data)." error: ".$e->getMessage());
            throw new Exception('服务器内部错误');
        }
        return $update;
    }

    /**
     * 修改用户默认地址
     *
     * @param int $userId
     * @param int $id
     * @return bool
     */
    public function updateDefaultAddressByUserid(int $userId, int $id)
    {
        $this->model->startTrans();
        try {
            // 修改该用户所有地址信息的默认数据
            $upall  = $this->editAll(['uid' => $userId], ['is_default' => 0]);
            // 修改该用户的默认地址
            $update = $this->edit($id, ['is_default' => 1]);
            $this->model->commit();
        } catch (\Exception $e) {
            $this->model->rollback();
            $this->errorLog("update default address user:$userId id:$id error: ".$e->getMessage());
            throw new Exception('服务器内部错误');
        }
        return true;
    }
}